import fs from 'fs';
import { fileURLToPath } from 'url'
import path from 'path'
import ts from 'rollup-plugin-typescript2'
import dts from 'rollup-plugin-dts'
import json from '@rollup/plugin-json'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import babel from '@rollup/plugin-babel'
import terser from '@rollup/plugin-terser'
import del from 'rollup-plugin-delete'
const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default fs.readdirSync(path.resolve(__dirname,'packages')).filter(dir => fs.statSync(path.resolve(__dirname, 'packages', dir)).isDirectory())
  .map(dir => {
    var filepath = path.resolve(__dirname, 'packages', dir);
    let pkg = fs.readFileSync(path.resolve(filepath, 'package.json'),{encoding:"utf-8"});
    pkg = JSON.parse(pkg);
    return [{
      input: path.resolve(filepath, 'src/index.ts'),
      output: [
        {
          file: path.resolve(filepath, pkg.main),
          format: 'cjs',
          sourcemap: true,
        },
        {
          file: path.resolve(filepath, pkg.module),
          format: 'esm',
          sourcemap: true,
        },
        {
          file: path.resolve(filepath, pkg.jsdelivr),
          format: 'umd',
          name: pkg.name,
          sourcemap: false,
        },
      ],
      plugins: [
        ts({
          tsconfig: path.resolve(__dirname, './tsconfig.json'),
          extensions: ['.js', '.ts'],
          "declaration": true,
        }),
        json(),
        resolve(),
        commonjs(),
        babel({
          babelHelpers: true,
          exclude: 'node_modules/**',
        }),
        terser(),
      ]
    },
    {
        input: path.resolve(filepath,"dist/index.d.ts"),
        output: [
          {
            file: path.resolve(filepath,"types/index.d.ts"),
            format: "es"
          }
        ],
        plugins: [
          dts(),
          del({
            targets: ['dist/src'],
            hook: 'buildEnd'
          })
        ],
      }
    ]
  }).reduce((arr,item) => {
        return arr.concat(item);
  },[])
